/*
 * ContribuyentesActualizarFrame.java
 *
 * Created on 4 de mayo de 2008, 12:45 PM
 */
package org.contribuyentes;

import org.mybeans.Sesion;
import org.mybeans.ContribuyentesBeans;
import java.sql.PreparedStatement;
import java.util.GregorianCalendar;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 *
 * @author  avbravo
 */
public class ContribuyentesCambioCedulaFrame extends javax.swing.JFrame {

    Sesion sesion;
     ContribuyentesBeans contribuyentesBeans;
boolean focoContribuyente = false;
    /** Creates new form ContribuyentesActualizarFrame */
    public ContribuyentesCambioCedulaFrame() {
        initComponents();
        sesion = new Sesion();
        contribuyentesBeans = new ContribuyentesBeans();
        /*
         * Fondo
         */

         
         
         

         
         
        /*
         * fondo
         */

        if (sesion.getCedulaContribuyente() == null || sesion.getCedulaContribuyente().equals("")) {
        } else {
            jTextFieldCedula.setText(sesion.getCedulaContribuyente());
            ValidarCedula();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldCedula = new javax.swing.JTextField();
        jTextFieldContribuyente = new javax.swing.JTextField();
        jTextFieldCedulaNueva = new javax.swing.JTextField();
        jButtonGuardar = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();
        jButtonLimpiar = new javax.swing.JButton();
        jButtonBuscarContribuyentes = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaMotivo = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cambiar Cedula");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
         

        jLabel1.setText("Cedula");

        jLabel2.setText("Contribuyente");

        jLabel3.setText("Nueva Cedula");

        jTextFieldCedula.setColumns(35);
        jTextFieldCedula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldCedulaActionPerformed(evt);
            }
        });

        jTextFieldContribuyente.setColumns(70);
        jTextFieldContribuyente.setEditable(false);

        jButtonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/save.png"))); // NOI18N
        jButtonGuardar.setToolTipText("Cambiar Cedula");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Regresar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/escoba.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar ");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        jButtonBuscarContribuyentes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/search.png"))); // NOI18N
        jButtonBuscarContribuyentes.setToolTipText("Buscar");
        jButtonBuscarContribuyentes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarContribuyentesActionPerformed(evt);
            }
        });

        jLabel4.setText("Motivo");

        jTextAreaMotivo.setColumns(20);
        jTextAreaMotivo.setRows(5);
        jScrollPane1.setViewportView(jTextAreaMotivo);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(58, 58, 58)
                                .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButtonBuscarContribuyentes, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldCedulaNueva, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextFieldContribuyente, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel4))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)
                        .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(80, 80, 80))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButtonBuscarContribuyentes)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldContribuyente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldCedulaNueva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel4))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(23, 23, 23))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 539, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed

    Limpiar();
}//GEN-LAST:event_jButtonLimpiarActionPerformed

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed

    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed

    try {

        String Cedula = this.jTextFieldCedula.getText();
        if (Cedula == null || Cedula.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese la cedula del contribuyente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldCedula.requestFocus();
            return;
        }
        String CedulaNueva = this.jTextFieldCedulaNueva.getText();
        if (CedulaNueva == null || CedulaNueva.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese la cedula nueva", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldCedulaNueva.requestFocus();
            return;
        }

        Cedula = Cedula.toLowerCase();
        CedulaNueva = CedulaNueva.toLowerCase();
        if (Cedula.equals(CedulaNueva)) {
            JOptionPane.showMessageDialog(this, "La cedula nueva debe ser diferente de la actual", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldCedulaNueva.requestFocus();
            return;
        }
        if (contribuyentesBeans.ConsultarSinMensaje(CedulaNueva) == true) {
            JOptionPane.showMessageDialog(this, "Existe un contribuyente con esa cedula \n No se puede cambiar \n Utilice otra cedula", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldCedulaNueva.requestFocus();
            return;
        }
String Motivo = jTextAreaMotivo.getText();
 if (Motivo == null || Motivo.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el motivo del cambio de cedula", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextAreaMotivo.requestFocus();
            return;
        }
/*
 * guardar los datos del cambio
 */
 if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
          String sql = "INSERT into cambioscedula VALUES(?,?,?,?,?,?)";
        PreparedStatement prest = sesion.con.prepareStatement(sql);

        prest.setString(1, Cedula);
        prest.setString(2, CedulaNueva);
        prest.setString(3, Motivo);
        prest.setString(4, sesion.getIdmunicipio());
        
        java.util.Calendar startDate = GregorianCalendar.getInstance();
        startDate.getTime();

        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        prest.setDate(5, mydate);
        prest.setString(6, sesion.getUsername());
        
        int count = prest.executeUpdate();
        sesion.con.close();
        /*
         *actualizar los registros en todas las tablas
         *
         */
    sql = "update contribuyentes set cedula = ?  where cedula = ? and idmunicipio =?";
        Actualizar(sql);
        //  <comercios>
        sql = "update   comercios set cedula = ?  where cedula = ? and idmunicipio =?";
        Actualizar(sql);

        //  <cierremensualvigenciasexpiradas>
        sql = "update   cierremensualvigenciasexpiradas set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";

        Actualizar(sql);

        // <cierremorosidadmensual>
        sql = "update   cierremorosidadmensual set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);
        //  <cierrerecargomensual>
        sql = "update   cierrerecargomensual set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);

        //  <morosidadmensual>
        sql = "update   morosidadmensual set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);

        //  <pagosanuales>
        sql = "update   pagosanuales set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);

        //  <pagosmensuales>
        sql = "update  pagosmensuales set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);

//  <recargomensual>
        sql = "update  recargomensual set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);

        //  <recibes>
        sql = "update  recibes set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);

        //  <remol>
        sql = "update  remolques set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);

        //  <vehicles>
        sql = "update  vehicles set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);

        //  <vigenciasexpiradas>
        sql = "update vigenciasexpiradas set id = ?  where id = ? and idmunicipio =? and tipoid='contribuyentes'";
        Actualizar(sql);
        JOptionPane.showMessageDialog(this, "Cambio de cedula realizado con exito", "Actualizado", JOptionPane.INFORMATION_MESSAGE);
        sesion.setCedulaContribuyente(CedulaNueva);


    } catch (Exception ex) {
        sesion.MostrarMensajeError("Error ", "Clase: PagosMensualesBeans.java\nBotonActualizar()\n " + ex.getMessage().toString());
    }
}//GEN-LAST:event_jButtonGuardarActionPerformed

    private void Actualizar(String sql) {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String Cedula = this.jTextFieldCedula.getText();
            String CedulaNueva = this.jTextFieldCedulaNueva.getText();
            PreparedStatement prest = sesion.con.prepareStatement(sql);
            prest.setString(1, CedulaNueva);
            prest.setString(2, Cedula);
            prest.setString(3, sesion.getIdmunicipio());
            int count = prest.executeUpdate();
            sesion.con.close();
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "Clase: ContribuyentesActualizarFrame.java\nActualizar()\n " + ex.getMessage().toString());
        }
    }
private void jButtonBuscarContribuyentesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarContribuyentesActionPerformed

    ContribuyentesBusquedaFrame contribuyentesBusquedaFrame = new ContribuyentesBusquedaFrame();
    contribuyentesBusquedaFrame.setLocationRelativeTo(null);
    contribuyentesBusquedaFrame.setVisible(true);
 focoContribuyente = true;
}//GEN-LAST:event_jButtonBuscarContribuyentesActionPerformed

private void jTextFieldCedulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCedulaActionPerformed

    ValidarCedula();

}//GEN-LAST:event_jTextFieldCedulaActionPerformed

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
    // TODO add your handling code here:
    try {

            if (focoContribuyente) {
                CargarContribuyentes();
            }

        focoContribuyente = false;
    } catch (Exception ex) {
        sesion.MostrarMensajeError("Error ", "Clase: PagosContribuyentesEventualesFrame.java\nBoton Actualizar Impuestos()\n " + ex.getMessage().toString());
    }
}//GEN-LAST:event_formWindowGainedFocus

    private void ValidarCedula() {
        try {
            String cedula = this.jTextFieldCedula.getText();
            sesion.setCedulaContribuyente(this.jTextFieldCedula.getText());
            if (contribuyentesBeans.Consultar(cedula) == true) {
                CargarContribuyentes();
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ContribuyentesCambioCedulaFrame().setVisible(true);
            }
        });
    }

    private void Limpiar() {
        this.jTextFieldCedula.setText("");
        this.jTextFieldContribuyente.setText("");
        this.jTextFieldCedulaNueva.setText("");
        jTextAreaMotivo.setText("");

    }

    public void CargarContribuyentes() {
        try {
            if (contribuyentesBeans.getActivo().equals("no")) {
                JOptionPane.showMessageDialog(this, "Este registro esta inactivo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            this.jTextFieldCedula.setText(contribuyentesBeans.getCedula());
            sesion.setCedulaContribuyente(this.jTextFieldCedula.getText());
            this.jTextFieldContribuyente.setText(contribuyentesBeans.getContribuyente());

            
            repaint();


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBuscarContribuyentes;
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextAreaMotivo;
    private javax.swing.JTextField jTextFieldCedula;
    private javax.swing.JTextField jTextFieldCedulaNueva;
    private javax.swing.JTextField jTextFieldContribuyente;
    // End of variables declaration//GEN-END:variables
}
